package com.example.springboot.controller;

import cn.hutool.core.util.StrUtil;
import com.example.springboot.dto.UserDTO;
import com.example.springboot.entity.Role;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import com.example.springboot.utils.AjaxResult;
import com.example.springboot.service.IUserService;
import com.example.springboot.entity.User;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.date.DateUtil;
import org.springframework.web.multipart.MultipartFile;
import com.example.springboot.utils.PageData;

import java.util.HashMap;
import java.util.Map;
import java.io.InputStream;
import java.net.URLEncoder;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author cpf
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody UserDTO userDTO, HttpServletRequest request) {
        try {
            String userAccount = userDTO.getUserAccount();
            String password = userDTO.getPassword();
            String ip = request.getRemoteAddr();
            if (StrUtil.isBlank(userAccount) || StrUtil.isBlank(password)) {
                return AjaxResult.error("参数错误");
            }
            // 本机访问
            if ("localhost".equalsIgnoreCase(ip) || "127.0.0.1".equalsIgnoreCase(ip) || "0:0:0:0:0:0:0:1".equalsIgnoreCase(ip)) {
                // 根据网卡取本机配置的IP
                InetAddress inet;
                inet = InetAddress.getLocalHost();
                ip = inet.getHostAddress();
            }else{
                ip = "127.0.0.1";
            }
            userDTO.setIp(ip);
            UserDTO dto = userService.login(userDTO);
            return AjaxResult.success("查询成功", dto);
        } catch (Exception e) {
//           e.printStackTrace();
            return AjaxResult.failure(e.getMessage());
        }
    }


    // 新增或者更新
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxResult save(@RequestBody User user) {
        try {
            //if (user.getId() == null) {
            //user.setTime(DateUtil.now());
            //user.setUser(TokenUtils.getCurrentUser().getUsername());
            //}
            User userData = userService.queryById(user.getId());
            if (userData == null) {
                //save
                userService.insert(user);
                return AjaxResult.success("添加成功！");
            } else {
                userService.update(user);
                return AjaxResult.success("修改成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.failure("请查看日志");
        }

    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public AjaxResult delete(@PathVariable Integer id) {
        List<Integer> ids = new ArrayList<>();
        ids.add(id);
        userService.deleteByIds(ids);
        return AjaxResult.success("删除成功");
    }

    @RequestMapping(value = "/del/batch", method = RequestMethod.DELETE)
    public AjaxResult deleteBatch(@RequestBody List<Integer> ids) {
        try {
            userService.deleteByIds(ids);
            return AjaxResult.success("删除成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.failure("请查看日志");
        }
    }

    @RequestMapping(value = "/findAll", method = RequestMethod.GET)
    public AjaxResult findAll() {
        try {
            Map<String, Object> param = new HashMap<>();
            List<User> userList = userService.queryAllInfo(param);
            return AjaxResult.success("查询成功", userList);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.failure("请查看日志");
        }
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public AjaxResult findOne(@PathVariable("id") Integer id) {
        try {
            User user = userService.queryById(id);
            return AjaxResult.success("查询成功", user);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.failure("请查看日志");
        }
    }

    @RequestMapping(value = "/username/{username}", method = RequestMethod.GET)
    public AjaxResult findOne(@PathVariable("username") String username) {
        try {
            Map<String, Object> param = new HashMap<>();
            param.put("userAccount", username);
            User user = userService.queryAllInfo(param).get(0);
            return AjaxResult.success("查询成功", user);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.failure("请查看日志");
        }
    }

    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public AjaxResult findPage(@RequestBody Map<String, Object> param) {
        try {

            //User currentUser = TokenUtils.getCurrentUser();
            //if (currentUser.getRole().equals("ROLE_USER")) {
            //queryWrapper.eq("user", currentUser.getUsername());
            //}
            int pageSize = Integer.parseInt(String.valueOf(param.get("pageSize")));
            int page = Integer.parseInt(String.valueOf(param.get("page")));
            int startIndex = (page - 1) * pageSize;
            param.put("pageIndex", startIndex);
            long count = userService.count(param);
            List<User> userList = userService.queryAllInfo(param);
            PageData pageData = new PageData(page, pageSize, userList, count);
            return AjaxResult.success("查询成功！", pageData);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.failure("请查看日志");
        }
    }

    /**
     * 导出接口
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void export(HttpServletResponse response) throws Exception {
        try {
            // 从数据库查询出所有的数据,查询条件为空
            Map<String, Object> param = new HashMap<>();
            List<User> list = userService.queryAllInfo(param);
            // 在内存操作，写出到浏览器
            ExcelWriter writer = ExcelUtil.getWriter(true);

            // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
            writer.write(list, true);

            // 设置浏览器响应的格式
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            String fileName = URLEncoder.encode("User信息表", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

            ServletOutputStream out = response.getOutputStream();
            writer.flush(out, true);
            out.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * excel 导入
     *
     * @param file
     * @throws Exception
     */
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public AjaxResult importFile(MultipartFile file) throws Exception {
        try {
            InputStream inputStream = file.getInputStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream);
            // 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
            List<User> list = reader.readAll(User.class);

            userService.insertBatch(list);
            return AjaxResult.success("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.failure("请查看日志");
        }
    }


}

